package com.czy.seed.mvc.home.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.czy.seed.mvc.home.entity.*;
import com.czy.seed.mvc.home.service.*;
import com.czy.seed.mvc.itextPdf.CreatePdf_MemorandInUniting;
import com.czy.seed.mvc.itextPdf.CreatePdf_Quotation;

import com.czy.seed.mvc.sys.entity.SysUser;
import com.czy.seed.mvc.sys.service.SysUserService;
import com.czy.seed.mvc.util.*;
import com.czy.seed.mybatis.base.QueryParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/home/purchase_orders")
public class PurchaseController {

    @Autowired
    private PurchaseOrdersService purchaseOrdersService;
    @Autowired
    private PurchaseDetailedListService purchaseDetailedListService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private CommodityService commodityService;
    @Autowired
    private MerchantService merchantService;

    @Autowired
    SystemProperties systemProperties;

    private String url = this.getClass().getClassLoader().getResource("").getPath() + "\\" + "static" + "\\" + "lib" + "\\" + "pdf" + "\\";

    public static Logger logger = LoggerFactory.getLogger(PurchaseController.class);

    /**
     * 查询所有采购单主单信息
     */
    @RequestMapping("/selectOrdersAll")
    public Res selectOrdersAll() {
        QueryParams queryParams = new QueryParams(PurchaseOrders.class);
        List<PurchaseOrders> purchaseOrders = null;
        try {
            purchaseOrders = purchaseOrdersService.selectListByParams(queryParams);
        } catch (Exception e) {

            logger.error("查询所有采购单信息出错：{}", e);
        }
        Map<String, Object> pageInfo = new HashMap<String, Object>(16);
        pageInfo.put("purchaseOrders", purchaseOrders);
        return Res.ok(pageInfo);
    }

    /**
     * 根据主单ID查询所关联的所有的清单
     */
    @RequestMapping("/selectPurchaseDetailedListAllByOrdersId")
    public Res selectPurchaseDetailedListAllByOrdersId(long ordersId) {
        Map<String, Object> pageInfo = new HashMap<String, Object>(16);
        QueryParams queryParams = new QueryParams(PurchaseDetailedList.class);
        QueryParams.Criteria criteria = queryParams.createCriteria();
        criteria.andEqualTo("ssdd_glgx", ordersId);
        List<PurchaseDetailedList> purchaseDetailedList = null;
        try {
            purchaseDetailedList = purchaseDetailedListService.selectListByParams(queryParams);
        } catch (Exception e) {
            logger.error("根据主单ID查询所关联的所有的清单信息出错：{}", e);
        }

        pageInfo.put("purchaseDetailedList", purchaseDetailedList);
        return Res.ok(pageInfo);
    }


    /**
     * 查询配置信息是否允许自定义添加商品信息
     */
    @RequestMapping("/configuration")
    public Res configuration() {
        Map<String, Object> pageInfo = new HashMap<>(16);
        pageInfo.put("addYourselfSwitch", systemProperties.getAddYourselfSwitch());
        return Res.ok(pageInfo);
    }


    /**
     * 根据主单ID查询所关联的所有的清单并且状态为待完成
     */
    @RequestMapping("/selectPurchaseDetailedListAllByOrdersIdAndType")
    public Res selectPurchaseDetailedListAllByOrdersIdAndType(HttpServletRequest request) {
        //主单ID
        String ordersId = request.getParameter("ordersId");
        QueryParams queryParams = new QueryParams(PurchaseDetailedList.class);
        QueryParams.Criteria criteria = queryParams.createCriteria();
        criteria.andEqualTo("ssdd_glgx", ordersId);
        criteria.andEqualTo("type", "待完成");
        List<PurchaseDetailedList> purchaseDetailedList = null;
        try {
            purchaseDetailedList = purchaseDetailedListService.selectListByParams(queryParams);
        } catch (Exception e) {
            logger.error("根据主单ID查询所关联的所有的清单并且状态为待完成信息出错：{}", e);
        }
        Map<String, Object> pageInfo = new HashMap<String, Object>(16);
        pageInfo.put("purchaseDetailedList", purchaseDetailedList);
        return Res.ok(pageInfo);
    }

    /**
     * 创建子单并且级联创建主单关键信息
     * 这个方法只适用于第一次创建采购单清单是用的
     */
    @RequestMapping("/insertDetailAndAddOrders4Frist")
    public Res insertDetailAndAddOrders4Frist(HttpServletRequest request) {
        Map<String, Object> pageInfo = new HashMap<>();
        try {
            pageInfo = purchaseOrdersService.insertDetailAndAddOrders4Frist_impl(request);
        } catch (Exception e) {
            pageInfo.put("message", e.getMessage());
            logger.error("查询所有采购单信息出错：{}", e);
        }
        return Res.ok(pageInfo);
    }

    /**
     * 根据主单ID增加子单
     */
    @RequestMapping("/addDetailByParentId")
    public Res addDetailByParentId(HttpServletRequest request) {
        Map<String, Object> pageInfo = new HashMap<>();
        try {
            pageInfo = purchaseOrdersService.addDetailByParentId_impl(request);
        } catch (Exception e) {
            pageInfo.put("message", e.getMessage());
            logger.error("根据主单ID增加子单出错：{}", e);
        }
        return Res.ok(pageInfo);
    }

    /**
     * 查询子单
     */
    @RequestMapping("/selectDetailById")
    public Res selectDetailById(HttpServletRequest request) {
        Map<String, Object> pageInfo = new HashMap<String, Object>();
        String object = request.getParameter("data");
        try {
            PurchaseDetailedList purchaseDetailedList = JSONObject.parseObject(object, PurchaseDetailedList.class);
            QueryParams queryParams = new QueryParams(PurchaseDetailedList.class);
            QueryParams.Criteria criteria = queryParams.createCriteria();
            criteria.andEqualTo("id", purchaseDetailedList.getId());
            List<PurchaseDetailedList> List = purchaseDetailedListService.selectListByParams(queryParams);
            if (List.size() > 0) {
                pageInfo.put("status", "false");
            } else {
                pageInfo.put("status", "true");
            }
            pageInfo.put("id", purchaseDetailedList.getId());
        } catch (Exception e) {
            logger.error("查询子单信息出错：{}", e);
        }
        return Res.ok(pageInfo);
    }

    /**
     * 更新子单
     */
    @RequestMapping("/updateDetailById")
    public Res updateDetailById(HttpServletRequest request) {
        Map<String, String> pageInfo = new HashMap<String, String>();
        try {
            pageInfo = purchaseOrdersService.updateDetailById_impl(request);
        } catch (Exception e) {
            pageInfo.put("message", e.getMessage());
            logger.error("更新子单信息出错：{}", e);
        }
        return Res.ok(pageInfo);
    }

    /**
     * 更新子单
     */
    @RequestMapping("/deleteDetailById")
    public Res deleteDetailById(HttpServletRequest request) {
        Map<String, String> pageInfo = new HashMap<String, String>();
        try {
            pageInfo = purchaseOrdersService.deleteDetailById_impl(request);
        } catch (Exception e) {
            pageInfo.put("message", e.getMessage());
            logger.error("更新子单信息出错：{}", e);
        }
        return Res.ok(pageInfo);
    }

    /**
     * 采购清单直接购买
     * 更新子单状态
     */
    @RequestMapping("/updateDetailById4type")
    public Res updateDetailById4type(HttpServletRequest request) {
        Map<String, String> pageInfo = new HashMap<String, String>();
        try {
            String object = request.getParameter("data");
            String type = request.getParameter("type");
            //更新子单
            PurchaseDetailedList purchaseDetailedList = JSONObject.parseObject(object, PurchaseDetailedList.class);
            pageInfo = purchaseOrdersService.updateDetailById4type_impl(type, purchaseDetailedList);
        } catch (Exception e) {
            pageInfo.put("message", e.getMessage());
            logger.error("采购清单直接购买出错：{}", e);
        }
        return Res.ok(pageInfo);

    }

    /**
     * 更新子单状态
     */
    @RequestMapping("/updateDetailtype")
    public Res updateDetailtype(HttpServletRequest request) {
        Map<String, String> pageInfo = new HashMap<String, String>();
        try {
            pageInfo = purchaseOrdersService.updateDetailtype_impl(request);
        } catch (Exception e) {
            pageInfo.put("message", e.getMessage());
            logger.error("更新子单状态信息出错：{}", e);
        }
        return Res.ok(pageInfo);
    }


    /**
     * 更新主单状态及其所有子弹状态
     */

    @RequestMapping("/updatePurchaseOrdersById4all")
    public Res updatePurchaseOrdersById4all(HttpServletRequest request) {
        Map<String, String> pageInfo = new HashMap<>();
        try {
            pageInfo = purchaseOrdersService.updatePurchaseOrdersById4all_impl(request);
        } catch (Exception e) {
            pageInfo.put("message", e.getMessage());
            logger.error("更新子单状态信息出错：{}", e);
        }
        return Res.ok(pageInfo);
    }


    /**
     * 更新主单
     */
    @RequestMapping("/updatePurchaseOrdersById")
    public Res updatePurchaseOrdersById(HttpServletRequest request) {
        Map<String, String> pageInfo = new HashMap<>();
        try {
            pageInfo = purchaseOrdersService.updatePurchaseOrdersById_impl(request);
        } catch (Exception e) {
            pageInfo.put("message", e.getMessage());
            logger.error("更新更新主单信息出错：{}", e);
        }
        return Res.ok(pageInfo);
    }

    /**
     * 删除主单
     * 删除主单后不需要再对主单所对应的子单处理，数据库中有级联触发器和外键
     */
    @RequestMapping("/deletePurchaseOrdersById")
    public Res deletePurchaseOrdersById(HttpServletRequest request) {
        Map<String, String> pageInfo = new HashMap<>();
        try {
            pageInfo = purchaseOrdersService.deletePurchaseOrdersById_impl(request);
        } catch (Exception e) {
            pageInfo.put("message", e.getMessage());
            logger.error("更新更新主单信息出错：{}", e);
        }
        return Res.ok(pageInfo);
    }

    /**
     * 查询采购单主单信息
     */
    @RequestMapping("/selectOrdersById")
    public Res selectOrdersById(long ordersId) {
        Map<String, Object> pageInfo = new HashMap<String, Object>(16);
        try {
            PurchaseOrders purchaseOrders = purchaseOrdersService.selectByPrimaryKey(ordersId);
            pageInfo.put("purchaseOrders", purchaseOrders);
        } catch (Exception e) {
            logger.error("查询采购单主单信息出错：{}", e);
        }
        return Res.ok(pageInfo);
    }

    //依据主单ID查询主单和清单的信息
    @RequestMapping("/selectOrdersAllById")
    public Res selectOrdersAllById(long ordersId) {
        Map<String, Object> pageInfo = new HashMap<String, Object>(16);
        try {
            PurchaseOrders purchaseOrders = purchaseOrdersService.selectByPrimaryKey(ordersId);
            pageInfo.put("purchaseOrders", purchaseOrders);
            QueryParams queryParams = new QueryParams(PurchaseDetailedList.class);
            QueryParams.Criteria criteria = queryParams.createCriteria();
            criteria.andEqualTo("ssdd_glgx", ordersId);
            List<PurchaseDetailedList> purchaseDetailedList = null;
            try {
                purchaseDetailedList = purchaseDetailedListService.selectListByParams(queryParams);
            } catch (Exception e) {
                logger.error("根据主单ID查询所关联的所有的清单信息出错：{}", e);
            }
            pageInfo.put("purchaseDetailedList", purchaseDetailedList);
        } catch (Exception e) {
            logger.error("查询采购单主单信息出错：{}", e);
        }
        return Res.ok(pageInfo);
    }

    /**
     * 查询自己创建的采购单主单信息
     */
    @RequestMapping("/selectOrdersByUser")
    public Res selectOrdersByUser() {
        Map<String, Object> pageInfo = new HashMap<String, Object>(16);
        QueryParams queryParams = new QueryParams(PurchaseOrders.class);
        QueryParams.Criteria criteria = queryParams.createCriteria();
        criteria.andEqualTo("creator_userid", PrincipalUtil.getLoginUser().getId());
        criteria.andEqualTo("type", "申请");
        try {
            List<PurchaseOrders> purchaseOrders = purchaseOrdersService.selectListByParams(queryParams);
            pageInfo.put("purchaseOrders", purchaseOrders);
        } catch (Exception e) {
            logger.error("查询采购单位创建的采购单主单信息失败：{}", e);
        }

        return Res.ok(pageInfo);
    }

    /**
     * 查询等待询价的采购单主单信息
     */
    @RequestMapping("/selectOrders4Quotation")
    public Res selectOrders4Quotation() {
        Map<String, Object> pageInfo = new HashMap<String, Object>(16);
        try {
            List<PurchaseOrders> purchaseOrders = purchaseOrdersService.selectpurchaseOrdersByUserbycreate(PrincipalUtil.getLoginUser().getId(), "审核通过");
            pageInfo.put("purchaseOrders", purchaseOrders);
        } catch (Exception e) {
            logger.error("查询等待询价的采购单主单信息失败：{}", e);
        }
        return Res.ok(pageInfo);
    }

    /**
     * 查询等待完成的采购单主单信息
     */
    @RequestMapping("/selectEnterOrders4Quotation")
    public Res selectEnterOrders4Quotation() {
        Map<String, Object> pageInfo = new HashMap<String, Object>(16);
        try {
            List<PurchaseOrders> purchaseOrders = purchaseOrdersService.selectpurchaseOrdersByUserbycreate(PrincipalUtil.getLoginUser().getId(), "待完成");
            pageInfo.put("purchaseOrders", purchaseOrders);
        } catch (Exception e) {
            logger.error("查询等待完成的采购单主单信息失败：{}", e);
        }
        return Res.ok(pageInfo);
    }

    /**
     * 采购办依据自己的ID在USER表中查询自己创建的用户ID
     * 根据这些用户ID再次查询自己所需要待审核的采购单信息
     */
    @RequestMapping("/selectOrdersByCreateUser")
    public Res selectOrdersByCreateUser(HttpServletRequest request) {
        String type = request.getParameter("type");
        Map<String, Object> pageInfo = new HashMap<String, Object>(16);
        try {
            List<PurchaseOrders> purchaseOrders = purchaseOrdersService.selectpurchaseOrdersByCreateUser(type, PrincipalUtil.getLoginUser().getId());
            pageInfo.put("purchaseOrders", purchaseOrders);
        } catch (Exception e) {
            logger.error("采购办依据自己的ID在USER表中查询自己创建的用户ID ,根据这些用户ID再次查询自己所需要待审核的采购单信息失败：{}", e);
        }
        return Res.ok(pageInfo);
    }

    /**
     * 查询可以被作废的单子
     */
    @RequestMapping("/selectOrdersByCreateUser4Close")
    public Res selectOrdersByCreateUser4Close() {
        Map<String, Object> pageInfo = new HashMap<String, Object>(16);
        try {
            QueryParams queryParams = new QueryParams(PurchaseOrders.class);
            QueryParams.Criteria criteria = queryParams.createCriteria();
            criteria.andEqualTo("creator_userid", PrincipalUtil.getLoginUser().getId());
            List list = new ArrayList();
            list.add("审核通过");
            list.add("结果确认");
            list.add("待完成");
            criteria.andIn("type",list);
            List<PurchaseOrders> purchaseOrders = purchaseOrdersService.selectListByParams(queryParams);
            pageInfo.put("purchaseOrders", purchaseOrders);
        } catch (Exception e) {
            logger.error("查询可以作废的采购单失败：{}", e);
        }
        return Res.ok(pageInfo);
    }

    /**
     * 提交审核
     * 根据主单ID一次将主单和子单全部状态改为   待审核
     */
    @RequestMapping("/toPassDetailByParentId")
    public Res toPassDetailByParentId(HttpServletRequest request) {
        Map<String, String> pageInfo = new HashMap<String, String>(16);
        try {
            pageInfo = purchaseOrdersService.toPassDetailByParentId_impl(request);
        } catch (Exception e) {
            pageInfo.put("message", e.getMessage());
            logger.error("提交审核信息出错：{}", e);
        }
        return Res.ok(pageInfo);
    }

    /**
     * 审核通过
     * 根据主单ID一次将主单和子单全部状态改为   审核通过
     */
    @RequestMapping("/toCenterDetailByParentId")
    public Res toCenterDetailByParentId(HttpServletRequest request) {
        Map<String, Object> pageInfo = new HashMap<String, Object>(16);
        try {
            pageInfo = purchaseOrdersService.toCenterDetailByParentId_impl(request, systemProperties.getSecondInquirySwitch());
        } catch (Exception e) {
            pageInfo.put("message", e.getMessage());
            logger.error("提交审核通过信息(根据主单ID一次将主单和子单全部状态改为审核通过)出错：{}", e);
        }
        return Res.ok(pageInfo);
    }

    /**
     * 创建子单并且级联创建主单关键信息
     * 这个方法只适用于第一次创建采购单清单是用的
     */
    @RequestMapping("/insertDetailAndAddOrders4ShopCar")
    public Res insertDetailAndAddOrders4ShopCar(HttpServletRequest request) {
        Map<String, Object> pageInfo = new HashMap<String, Object>(16);
        try {
            pageInfo = purchaseOrdersService.establish(request);
            pageInfo.put("flag", "true");
            pageInfo.put("message", "创建采购单成功");
        } catch (Exception e) {
            pageInfo.put("flag", "false");
            pageInfo.put("message", e.getMessage());
            logger.error("创建子单并且级联创建主单关键信息(第一次创建采购单清单是用)出错：{}", e);
        }

        return Res.ok(pageInfo);
    }

    /**
     * 取 已经可以打印通知书的列表
     * 列表分为两部分，一部分是清单列表中的结果确认（直接购买）
     * 另一部分是经过询价结束之后的关联清单
     * 之后两部分合并在一起
     */
    @RequestMapping("/selectOrdersByCreateUser4ResultValidation")
    public Res selectOrdersByCreateUser4ResultValidation() {
        Map<String, Object> pageInfo = new HashMap<String, Object>(16);
        try {
            List<PurchaseOrders> purchaseOrders = purchaseOrdersService.selectpurchaseOrdersByCreateUser_(1, PrincipalUtil.getLoginUser().getId(), "结果确认");
            pageInfo.put("purchaseOrders", purchaseOrders);
        } catch (Exception e) {
            logger.error("查询打印任务信息出错：{}", e);
        }
        return Res.ok(pageInfo);
    }

    /**
     * 查询采购办处理的单子和供应商自己的单子
     */
    @RequestMapping("/selectMemorandInUniting")
    public Res selectMemorandInUniting() {
        Map<String, Object> pageInfo = new HashMap<String, Object>(16);
        try {
            List<PurchaseOrders> purchaseOrders = purchaseOrdersService.selectMemorandInUniting(PrincipalUtil.getLoginUser().getId(), PrincipalUtil.getLoginUser().getId());
            pageInfo.put("purchaseOrders", purchaseOrders);
            if (purchaseOrders.size() < 0) {
                pageInfo.put("message", "没有符合条件的数据");
            }
        } catch (Exception e) {
            logger.error("查询采购办处理的单子和供应商自己的单子信息出错：{}", e);
        }
        return Res.ok(pageInfo);
    }


    /**
     * 查询确认通知单纤细信息
     */
    @RequestMapping("/selectOrdersValidation")
    public Res selectOrdersValidation(HttpServletRequest request) {
        String ordersId = request.getParameter("ordersId");
        Map<String, Object> pageInfo = new HashMap<String, Object>(16);
        try {
            List<PurchaseOrderDetailVo> purchaseOrderDetailVosList = dataConversion(ordersId);
            if (purchaseOrderDetailVosList.size() < 0) {
                pageInfo.put("message", "没有查询到可以展示的打印确认通知书的数据！");
            } else {
                pageInfo.put("purchaseOrders", purchaseOrderDetailVosList);
                pageInfo.put("message", "操作成功！");
            }
        } catch (Exception e) {
            pageInfo.put("message", e.getMessage());
            logger.error("查询确认通知单信息出错：{}", e);
        }
        return Res.ok(pageInfo);
    }

    /**
     * 查询合同信息
     */
    @RequestMapping("/selectMemorandInUnitingPring")
    public Res selectMemorandInUnitingPring(HttpServletRequest request) {
        Map<String, Object> pageInfo = new HashMap<String, Object>(16);
        try {
            String ordersId = request.getParameter("ordersId");

            List<PurchaseOrderDetailVo> purchaseOrderDetailVosList = dataConversion(ordersId);
            pageInfo.put("purchaseOrders", purchaseOrderDetailVosList);
        } catch (Exception e) {
            pageInfo.put("message", e.getMessage());
            logger.error("查询合同信息出错：{}", e);
        }
        return Res.ok(pageInfo);
    }


    public List<PurchaseOrderDetailVo> dataConversion(String ordersId) {
        List<PurchaseOrderDetailVo> purchaseOrderDetailVosList = new ArrayList<>();
        QueryParams queryParams = new QueryParams(PurchaseOrders.class);
        QueryParams.Criteria criteria = queryParams.createCriteria();
        criteria.andEqualTo("id", Long.parseLong(ordersId));
        try {
            if ("finalist".equals(PrincipalUtil.getLoginUserRoles().get(0).getAuthority())) {
                QueryParams queryParam = new QueryParams(Merchant.class);
                QueryParams.Criteria criterias = queryParam.createCriteria();
                criterias.andEqualTo("userId", PrincipalUtil.getLoginUser().getId());
                List<Merchant> merchants = merchantService.selectListByParams(queryParam);
                criteria.andCondition(" PURCHASEDETAILEDLISTLIST.MERCHANTID= " + merchants.get(0).getId());
            }
        } catch (Exception e) {
            logger.error("商家查询生成通知单信息失败！");
        }
        criteria.andCondition(" PURCHASEDETAILEDLISTLIST.TYPE IN ('结果确认','待完成','已完成','等待确认单') ");
        List<PurchaseOrders> purchaseOrders = purchaseOrdersService.selectListRelativeByParams(queryParams);

        for (PurchaseDetailedList purchaseDetailedList : purchaseOrders.get(0).getPurchaseDetailedListList()) {
            PurchaseOrderDetailVo purchaseOrderDetailVo = new PurchaseOrderDetailVo();
            purchaseOrderDetailVo.setId(purchaseOrders.get(0).getId());
            purchaseOrderDetailVo.setDetailsId(purchaseDetailedList.getId());
            purchaseOrderDetailVo.setPmmc(purchaseDetailedList.getPmmc());
            purchaseOrderDetailVo.setBrand(purchaseDetailedList.getGoodsName());
            purchaseOrderDetailVo.setGgxh(purchaseDetailedList.getGgxh());
            purchaseOrderDetailVo.setNum(Math.toIntExact(purchaseDetailedList.getSl()));
            purchaseOrderDetailVo.setDj(new BigDecimal(purchaseDetailedList.getDj()));
            purchaseOrderDetailVo.setTotal(new BigDecimal(purchaseDetailedList.getZj()));
            purchaseOrderDetailVo.setGmfs(purchaseDetailedList.getGmfs());
            purchaseOrderDetailVo.setResultvalidationpath(purchaseDetailedList.getResultvalidationpath());
            purchaseOrderDetailVo.setResultvalidationname(purchaseDetailedList.getResultvalidationname());
            purchaseOrderDetailVo.setCompany_name(purchaseDetailedList.getMerchantid() + "");//TODO 商家名称
            purchaseOrderDetailVo.setUsername(purchaseOrders.get(0).getSqdwfzr());
            purchaseOrderDetailVo.setEntryName(purchaseOrders.get(0).getEntry_name());
            purchaseOrderDetailVosList.add(purchaseOrderDetailVo);
            purchaseOrderDetailVo.setMemorandinunitingname(purchaseDetailedList.getMemorandinunitingname());
            purchaseOrderDetailVo.setMemorandinunitingpath(purchaseDetailedList.getMemorandinunitingpath());

        }
        return purchaseOrderDetailVosList;
    }

    //生成确认报告
    @RequestMapping("/createOrdersValidation")
    public Res createOrdersValidation(HttpServletRequest request) {
        String product = request.getParameter("shopData");
        PurchaseOrderDetailVo purchaseOrderDetailVo = JSON.parseObject(product, PurchaseOrderDetailVo.class);
        //设置日期格式
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddhhmmssSSS");
        //设置日期格式
        SimpleDateFormat df1 = new SimpleDateFormat("yyyy年MM月dd日");
        String fileName = df.format(new Date()) + ".pdf";
        String path = url + fileName;
        String quote_unit = purchaseOrderDetailVo.getCompany_name();
        String name = purchaseOrderDetailVo.getEntryName();
        String lastTime = "            ";
        try {
            lastTime = purchaseOrderDetailVo.getDeadline().substring(0, 10);
        } catch (Exception e) {
            logger.error("这个异常不用管，原因是直接购买无法取到截止送货时间：{}", e);
        }
        List<PurchaseOrderDetailVo> list = new ArrayList<PurchaseOrderDetailVo>();
        list.add(purchaseOrderDetailVo);
        String cgr = purchaseOrderDetailVo.getUsername();
        String cgdw = purchaseOrderDetailVo.getUsername();
        String createTime = String.valueOf(df1.format(new Date()));
        String cjjedaxie = "";
        try {
            cjjedaxie = NumberToCN.number2CNMontrayUnit(purchaseOrderDetailVo.getTotal());
        } catch (Exception e) {

        }
        String cjjexx = String.valueOf(purchaseOrderDetailVo.getTotal());
        String frdb = "     ";
        String lsTime = "  年   月    日";
        Map<String, Object> pageInfo = null;
        CreatePdf_Quotation cf = new CreatePdf_Quotation();
        try {
            cf.createPdf(url, path, quote_unit, name, lastTime, list, cgr, cgdw, createTime, cjjedaxie, cjjexx, frdb, lsTime);
            pageInfo = purchaseOrdersService.createOrdersValidation_impl("等待确认单", purchaseOrderDetailVo.getDetailsId(), fileName, "../lib/pdf/" + fileName.replaceAll(".pdf", ".zip"), purchaseOrderDetailVo, path);
        } catch (Exception e) {
            pageInfo.put("message", e.getMessage());
            logger.error("生成确认报告出错：{}", e);
        }

        //更新清单表的状态和PDF名称路径等
        return Res.ok(pageInfo);

    }


    //打印合同
    @RequestMapping("/createMemorandInUniting")
    public Res createMemorandInUniting(HttpServletRequest request) {
        String product = request.getParameter("shopData");
        PurchaseOrderDetailVo purchaseOrderDetail_ = JSON.parseObject(product, PurchaseOrderDetailVo.class);
        List<PurchaseOrderDetailVo> purchaseOrderDetailVo = purchaseOrdersService.selectmemorInUniting(purchaseOrderDetail_.getDetailsId());
        String dwmc = "";
        String xfmc = "";
        String lastTime = "";
        String adress = "";
        String name = "";
        String rmb = "";
        Long purchaseid = purchaseOrderDetail_.getId();
        Long ordersid = purchaseOrderDetail_.getDetailsId();
        //设置日期格式
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddhhmmssSSS");
        //设置日期格式
        SimpleDateFormat df1 = new SimpleDateFormat("yyyy年MM月dd日");
        String fileName = "m_" + df.format(new Date()) + ".pdf";
        String path = url + fileName;
        //处理list
        List<PurchaseOrderDetailVo> purchase = new ArrayList<PurchaseOrderDetailVo>();
        for (PurchaseOrderDetailVo ls : purchaseOrderDetailVo) {
            xfmc = ls.getQuote_unit();
            lastTime = ls.getConsingment_time();
            adress = ls.getConsingment_adress();
            name = "";
            PurchaseOrderDetailVo lsvo = new PurchaseOrderDetailVo();
            NumberToCharArray toarray = new NumberToCharArray();
            lsvo.setPmmc(ls.getPmmc());
            lsvo.setGgxh(ls.getGgxh());
            lsvo.setJscs(ls.getJscs());
            lsvo.setNum(ls.getNum());
            lsvo.setDj(ls.getDj());
            lsvo.setCommodity_mak_prc(ls.getCommodity_mak_prc());
            rmb = NumberToCN.number2CNMontrayUnit(ls.getTotal());
            char[] chars = toarray.numberToChar(ls.getTotal().toString());
            lsvo.setSw(String.valueOf(chars[0]));
            lsvo.setW(String.valueOf(chars[1]));
            lsvo.setQ(String.valueOf(chars[2]));
            lsvo.setB(String.valueOf(chars[3]));
            lsvo.setS(String.valueOf(chars[4]));
            lsvo.setY(String.valueOf(chars[5]));
            lsvo.setJ(String.valueOf(chars[6]));
            lsvo.setF(String.valueOf(chars[7]));
            purchase.add(lsvo);
        }
        Map<String, Object> pageInfo = new HashMap<String, Object>(16);
        CreatePdf_MemorandInUniting cm = new CreatePdf_MemorandInUniting();
        try {
            cm.creatememorand(url, path, dwmc, xfmc, lastTime, purchase, adress, name, rmb);
            pageInfo = purchaseOrdersService.createMemorandInUniting_impl("待完成", ordersid, fileName, "../lib/pdf/" + fileName.replaceAll(".pdf", ".zip"), purchaseid, path);
        } catch (Exception e) {
            pageInfo.put("message", e.getMessage());
            logger.error("生成合同出错：{}", e);
        }
        return Res.ok(pageInfo);
    }



    /**
     * 查询采购单主单信息
     */
    @RequestMapping("/selectOrdersById4Excel")
    public Res selectOrdersById4Excel(long ordersId) {
        Map<String, Object> pageInfo = new HashMap<String, Object>(16);
        try {
            PurchaseOrders purchaseOrders = purchaseOrdersService.selectByPrimaryKey(ordersId);
            String cgys = "¥ " + purchaseOrders.getBhdget_amount() + "（大写：" + NumberToCN.number2CNMontrayUnit(new BigDecimal(purchaseOrders.getBhdget_amount() + "")) + ")";
            purchaseOrders.setYs(cgys);
            String nr = "经审核，同意该项目实行    " + purchaseOrders.getCgxs() + "    采购形式，采用   " + purchaseOrders.getZfcgfs() + "   采购方式，委托    " + purchaseOrders.getWtdljg() + "    实施采购。";
            String cgliebie = purchaseOrders.getCategory();
            if ("货物".equals(cgliebie)) {
                cgliebie = "货物（√）  工程（  ）  服务（ ）";
            } else if ("工程".equals(cgliebie)) {
                cgliebie = "货物（ ）  工程（√）  服务（ ）";
            } else {
                cgliebie = "货物（ ）  工程（ ）  服务（√）";
            }
            purchaseOrders.setCategory(cgliebie);
            String cgxs = purchaseOrders.getCgxs();
            if ("政府集中采购".equals(cgxs)) {
                cgxs = "政府集中采购（√）  部门集中采购（ ）  分散采购（ ）";
            } else if ("部门集中采购".equals(cgxs)) {
                cgxs = "政府集中采购（ ）  部门集中采购（√）  分散采购（ ）";
            } else {
                cgxs = "政府集中采购（ ）  部门集中采购（ ）  分散采购（√）";
            }
            purchaseOrders.setCgxs(cgxs);
            String wtdljg = purchaseOrders.getWtdljg();
            if ("政府集中采购机构".equals(wtdljg)) {
                wtdljg = "委托代理机构：政府集中采购机构（√）    社会代理机构（  ）";
            } else {
                wtdljg = "委托代理机构：政府集中采购机构（  ）    社会代理机构（√）";
            }
            purchaseOrders.setWtdljg(wtdljg);
            String cgfs = purchaseOrders.getZfcgfs();
            switch (cgfs) {
                case "公开招标":
                    cgfs = "公开招标（√） 邀请招标（ ） 竞争性谈判（ ） 询价（ ） 单一来源（ ） 竞争性磋商（ ）  协议供货（ ）  定点采购（ ）";
                    break;
                case "邀请招标":
                    cgfs = "公开招标（ ） 邀请招标（√） 竞争性谈判（ ） 询价（ ） 单一来源（ ） 竞争性磋商（ ）  协议供货（ ）  定点采购（ ）";
                    break;
                case "竞争性谈判":
                    cgfs = "公开招标（ ） 邀请招标（ ） 竞争性谈判（√） 询价（ ） 单一来源（ ） 竞争性磋商（ ）  协议供货（ ）  定点采购（ ）";
                    break;
                case "询价":
                    cgfs = "公开招标（ ） 邀请招标（ ） 竞争性谈判（ ） 询价（√） 单一来源（ ） 竞争性磋商（ ）  协议供货（ ）  定点采购（ ）";
                    break;
                case "单一来源":
                    cgfs = "公开招标（ ） 邀请招标（ ） 竞争性谈判（ ） 询价（ ） 单一来源（√） 竞争性磋商（ ）  协议供货（ ）  定点采购（ ）";
                    break;
                case "竞争性磋商":
                    cgfs = "公开招标（ ） 邀请招标（ ） 竞争性谈判（ ） 询价（ ） 单一来源（ ） 竞争性磋商（√）  协议供货（ ）  定点采购（ ）";
                    break;
                case "协议供货":
                    cgfs = "公开招标（ ） 邀请招标（ ） 竞争性谈判（ ） 询价（ ） 单一来源（ ） 竞争性磋商（ ）  协议供货（√）  定点采购（ ）";
                    break;
                default:
                    cgfs = "公开招标（ ） 邀请招标（ ） 竞争性谈判（ ） 询价（ ） 单一来源（ ） 竞争性磋商（ ）  协议供货（ ）  定点采购（√）";
                    break;
            }

            purchaseOrders.setZfcgfs(cgfs);
            purchaseOrders.setNr(nr);
            pageInfo.put("purchaseOrders", purchaseOrders);
        } catch (Exception e) {
            logger.error("查询采购单主单信息出错：{}", e);
        }
        return Res.ok(pageInfo);
    }


    @RequestMapping("/queryAllDatas")
    public Res queryAllDatas(String cond, String goodsName, String GMFS, String entryName, String contact) {
        Map<String, Object> pageInfo = new HashMap<String, Object>(16);
        try {
            //判断是什么角色登录office采购办，unit采购单位，finalist商家
            String role = PrincipalUtil.getLoginUserRoles().get(0).getAuthority();
            QueryParams queryParams = new QueryParams(PurchaseOrders.class);
            QueryParams.Criteria criteria = queryParams.createCriteria();
            criteria.andLike("entry_name", "%" + entryName + "%");
            criteria.andLike("company_name", "%" + contact + "%");
            criteria.andCondition(" purchaseDetailedListList.type = '" + cond +
                    "' and purchaseDetailedListList.GMFS like '%" + GMFS + "%'" + " and purchaseDetailedListList.GOODS_NAME like '%" + goodsName + "%'");
            switch (role) {
                case "unit":
                    criteria.andCondition("  purchaseDetailedListList.CREATEUSERID =" + PrincipalUtil.getLoginUser().getId());
                    break;
                case "office":
                    List<SysUser> userList = sysUserService.presentUser(PrincipalUtil.getLoginUser().getId(), "unit");
                    List<Long> longs = new ArrayList<>();
                    userList.stream().forEach(string -> {
                        longs.add(string.getId());
                    });
                    criteria.andCondition("  purchaseDetailedListList.CREATEUSERID in" + " (" + longs.toString().substring(1, longs.toString().length() - 1) + ")");
                    break;
                case "finalist":
                    QueryParams queryPara = new QueryParams(Merchant.class);
                    QueryParams.Criteria criterias = queryPara.createCriteria();
                    criterias.andEqualTo("userId", PrincipalUtil.getLoginUser().getId());
                    List<Merchant> merchants = merchantService.selectListByParams(queryPara);
                    List<Long> longList = new ArrayList<>();
                    merchants.stream().forEach(string -> {
                        longList.add(string.getId());
                    });
                    criteria.andCondition("  purchaseDetailedListList.MERCHANTID in" + " (" + longList.toString().substring(1, longList.toString().length() - 1) + ")");
                    break;
                default:
                    break;

            }

            List<PurchaseOrders> purchaseOrders = purchaseOrdersService.selectListRelativeByParams(queryParams);
            pageInfo.put("queryAllData4PurchaseVoList", purchaseOrders);
        } catch (Exception e) {
            pageInfo.put("message", e.getMessage());
            logger.error("查询直接购买采购单单信息出错：{}", e);
        }
        return Res.ok(pageInfo);
    }

    @RequestMapping("/selectContrastDetail")
    public Res selectContrastDetail(HttpServletRequest request) {
        Map<String, Object> pageInfo = new HashMap<String, Object>();
        String object = request.getParameter("data");
        try {
            PurchaseDetailedList purchaseDetailedList = JSONObject.parseObject(object, PurchaseDetailedList.class);
            QueryParams queryParams = new QueryParams(OrderDetail.class);
            QueryParams.Criteria criteria = queryParams.createCriteria();
            criteria.andEqualTo("id", purchaseDetailedList.getOrderCarGlgx());
            OrderDetail orderDetail = orderDetailService.selectOneByParams(queryParams);
            if (orderDetail != null && purchaseDetailedList.getOrderCarGlgx() != null) {
                QueryParams queryParams1 = new QueryParams(Commodity.class);
                QueryParams.Criteria criteria1 = queryParams1.createCriteria();
                criteria1.andCondition("id in(" + orderDetail.getComparisonid() + ")");
                List<Commodity> commodity = commodityService.selectListByParams(queryParams1);
                pageInfo.put("commodity", commodity);
            }
        } catch (Exception e) {
            logger.error("查询对比信息出错：{}", e);
        }
        return Res.ok(pageInfo);
    }

    /**
     * 查询需要处理的合同和通知书数量
     */

    @RequestMapping("/selectSum")
    public Res selectSum(HttpServletRequest request) {
        Map<String, Object> pageInfo = new HashMap<String, Object>();
        try {
            int tt = purchaseDetailedListService.selectSum(PrincipalUtil.getLoginUser().getId());
            pageInfo.put("tt", tt);
        } catch (Exception e) {
            logger.error("查询合同和通知书信息出错：{}", e);
        }
        return Res.ok();
    }

}
